package com.fingard.dsp.bank.directbank.cscb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;


/**
 * 长沙银行-公共方法
 * @author alan
 * @date 2020-05-18
 * @version 1.0
 */
public class CSCB01Base extends DirectBase implements ITcpClient {

    protected static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    protected static String separator = "|";

    protected void writeCommonHeader(XmlTextWriter xmlWriter, CSCB01Header p_bankHeader) throws Exception {
        xmlWriter.writeStartElement("ap");
        xmlWriter.writeStartElement("head");
        xmlWriter.writeElementString("tr_code", p_bankHeader.trCode, true);
        xmlWriter.writeElementString("cms_corp_no", "", true);//m:企业不需要赋企，由银企前置机进行赋值。
        xmlWriter.writeElementString("user_no", "", true);//m:企业不需要赋企，由银企前置机进行赋值。
        xmlWriter.writeElementString("org_code", "", true);//m:企业不需要赋企，由银企前置机进行赋值。
        xmlWriter.writeElementClosed("serial_no");//c:由银企直联系统产生（交易流水号）
        xmlWriter.writeElementString("req_no", p_bankHeader.reqNo, true);//企业erp的流水号(流水号)
        Date date = new Date();
        xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(date));
        xmlWriter.writeElementString("tr_time", Format.Time6Format.format(date));
        xmlWriter.writeElementString("channel", "5");//erp送‘5’
        xmlWriter.writeElementString("sign", "1");
        xmlWriter.writeElementString("file_flag", p_bankHeader.fileFlag);//0-报文1-文件
        xmlWriter.writeElementString("reserved", "", true);
        xmlWriter.writeEndElement();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr) throws Exception {
        return sendToBank(p_reqStr,null,null);
    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr,String transType,String commandCode) throws Exception {
        byte[] tmpBytes = p_reqStr.getBytes(getCharset());
        int XMLlength = tmpBytes.length + 2;
        StringBuilder reqContext = new StringBuilder(p_reqStr).insert(0, String.format("%010d", XMLlength) + "00");
        //发送银行前置
        String[] retStr = new String[]{"", ""};
        WriteBankUrlLogLn("请求银行的地址" + bankFront.serverIP + ":" + bankFront.serverPort);
        WriteBankLogStep2(reqContext.toString());

        //后置挡板
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, p_reqStr, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        tmpClient.timeoutMil = 300000;
        TcpReceiver tmpReceiver = tmpClient.sendMessage(reqContext.toString(), getCharset());
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(getCharset());
        if(StringHelper.isNullOrEmpty(retStr[1])){
        	retStr[1] = tmpReceiver.getConnMsg();
        }else{
        	retStr[1] = tmpReceiver.getFullString(getCharset());
        	int idx = retStr[1].indexOf("<ap>");
        	if(idx != -1){
        		retStr[1] = retStr[1].substring(idx);
        	}
        }
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</ap>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
